/*
 * All rights Reserved, Copyright (C) WANGJIAN LIMITED 2019
 * FileName: WebLogAspect.java
 * Version:  $Revision$
 * Modify record:
 * NO. |     Date       |    Name         |      Content
 * 1   | 2019年7月25日        | JFTT)wangjian    | original version
 */
package com.pl.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.pl.bean.LoggerEntity;
import com.pl.common.Constant.sessionKey;

/**
 * class name:WebLogAspect <BR>
 * class description: please write your description <BR>
 * Remark: <BR>
 * @version 1.00 2019年7月25日
 * @author JFTT)wangjian
 */
@Aspect
@Component
public class WebLogAspect {
	
	private static Logger log = LogManager.getLogger();
	
	//暂存日志类的key
	private final String rk = "WebLogAspect_entity"; 

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.curative.lrms.action.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        
        // 记录下请求内容
        //System.out.println("请求URL : " + req.getRequestURL().toString());
        //System.out.println("HTTP_METHOD : " + req.getMethod());
        //System.out.println("IP : " + req.getRemoteAddr());
        //System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        
        LoggerEntity entity = new LoggerEntity();
        entity.setUrl(request.getRequestURL().toString());
        entity.setSessionId(attributes.getSessionId());
        entity.setStartTime(System.currentTimeMillis()+"");
        entity.setUserId(request.getSession().getAttribute(sessionKey.OAUTH_USER_ID.getValue())+"");
        
        //记录参数
        Map<String, Object> paraMap = new HashMap<String, Object>();
        
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        
        for (int i = 0; i < joinPoint.getArgs().length; i++) {
        	//参数的值
        	Object paramVal = joinPoint.getArgs()[i];
			if(paramVal instanceof HttpServletRequest || paramVal instanceof HttpServletResponse || paramVal instanceof HttpSession) {
				
			}else {
				//参数名称，参数值
				paraMap.put(methodSignature.getParameterNames()[i], paramVal);
			}
		}
        entity.setParamData(JSON.toJSONString(paraMap));
        request.setAttribute(rk, entity);
        
        log.debug("发起请求 doBefore URL={} userId={} entity={}", entity.getUrl(), entity.getUserId(), JSON.toJSONString(entity));
    }

	/*
	 * @AfterReturning(returning="ret", pointcut = "webLog()") public void
	 * doAfterReturning(Object ret) throws Throwable { // 处理完请求，返回内容
	 * ServletRequestAttributes attributes = (ServletRequestAttributes)
	 * RequestContextHolder.getRequestAttributes(); HttpServletRequest request =
	 * attributes.getRequest();
	 * 
	 * LoggerEntity entity = (LoggerEntity) request.getAttribute(rk);
	 * entity.setEndTime(System.currentTimeMillis()+"");
	 * entity.setReturnData(JSON.toJSONString(ret));
	 * 
	 * log.debug("请求返回 doAfterReturning URL={} userId={} entity={}",
	 * entity.getUrl(), entity.getUserId(), JSON.toJSONString(entity)); }
	 */
}
